package com.wing.device.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.device.dao.DeviceAttributeCategoryDao;
import com.wing.device.model.entity.DeviceAttributeCategory;
import com.wing.device.model.request.DeviceAttributeCategoryForm;
import com.wing.device.model.response.DeviceAttributeCategoryVO;
import com.wing.product.model.entity.ProductAttributeCategory;
import com.wing.product.model.request.ProductAttributeCategoryForm;
import com.wing.product.model.response.NodeDataVO;
import com.wing.product.model.response.ProductAttributeCategoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备属性分类-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class DeviceAttributeCategoryServiceImpl extends ServiceImpl<DeviceAttributeCategoryDao, DeviceAttributeCategory> implements DeviceAttributeCategoryService {

    private static long ROOT_ID=-1l;

    @Override
    public int add(DeviceAttributeCategoryForm deviceAttributeCategoryForm) {

        //校验

        DeviceAttributeCategory deviceAttributeCategory =new DeviceAttributeCategory();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(DeviceAttributeCategory.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(deviceAttributeCategoryForm, deviceAttributeCategory, copyOptions);
        if (deviceAttributeCategoryForm.getParentId()!=-1){
            DeviceAttributeCategory deviceAttributeCategoryParent=new DeviceAttributeCategory();
            deviceAttributeCategoryParent.setId(deviceAttributeCategoryForm.getParentId());
            deviceAttributeCategoryParent.setHasChild(true);
            if (deviceAttributeCategoryForm.getIsDeleted()){
                deviceAttributeCategoryParent.setHasEnableChild(true);
            }
            baseMapper.updateById(deviceAttributeCategoryParent);
        }
        return baseMapper.insert(deviceAttributeCategory);
    }

    @Override
    public List<DeviceAttributeCategoryVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<DeviceAttributeCategoryVO> pageList4app(Page page, Map<String, Object> params) {
        List<DeviceAttributeCategoryVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public DeviceAttributeCategoryVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }


    @Override
    @Transactional
    public int del(Long id) {
        DeviceAttributeCategoryVO deviceAttributeCategoryVO=baseMapper.get4appById(id);
        if (deviceAttributeCategoryVO!=null){
            int delCount=baseMapper.deleteById(id);
            if (deviceAttributeCategoryVO.getParentId()!=ROOT_ID){
                int count=baseMapper.selectCount(new QueryWrapper<DeviceAttributeCategory>().eq("parent_id",deviceAttributeCategoryVO.getParentId()));
                if (count==0){
                    DeviceAttributeCategory deviceAttributeCategoryParent=new DeviceAttributeCategory();
                    deviceAttributeCategoryParent.setId(deviceAttributeCategoryVO.getParentId());
                    deviceAttributeCategoryParent.setHasChild(false);
                    deviceAttributeCategoryParent.setHasEnableChild(false);
                    baseMapper.updateById(deviceAttributeCategoryParent);
                }
            }

            return delCount;
        }
        return 0;
    }

    @Override
    @Transactional
    public int enable(Long id) {
        DeviceAttributeCategoryVO deviceAttributeCategoryVO=baseMapper.get4appById(id);
        if (deviceAttributeCategoryVO!=null){
            DeviceAttributeCategory deivceAttributeCategory=new DeviceAttributeCategory();
            deivceAttributeCategory.setId(id);
            deivceAttributeCategory.setIsDeleted(true);
            int updateCount=baseMapper.updateById(deivceAttributeCategory);
            if (deviceAttributeCategoryVO.getParentId()!=ROOT_ID){
                DeviceAttributeCategory deviceAttributeCategoryParent=new DeviceAttributeCategory();
                deviceAttributeCategoryParent.setId(deviceAttributeCategoryVO.getParentId());
                deviceAttributeCategoryParent.setHasEnableChild(true);
                baseMapper.updateById(deviceAttributeCategoryParent);
            }

            return updateCount;
        }

        return 0;
    }

    @Override
    @Transactional
    public int disable(Long id) {
        DeviceAttributeCategoryVO deviceAttributeCategoryVO=baseMapper.get4appById(id);
        if (deviceAttributeCategoryVO!=null){
            DeviceAttributeCategory deviceAttributeCategory=new DeviceAttributeCategory();
            deviceAttributeCategory.setId(id);
            deviceAttributeCategory.setIsDeleted(false);
            int updateCount=baseMapper.updateById(deviceAttributeCategory);
            if (deviceAttributeCategoryVO.getParentId()!=ROOT_ID){
                int count=baseMapper.selectCount(new QueryWrapper<DeviceAttributeCategory>().eq("parent_id",deviceAttributeCategoryVO.getParentId()).eq("is_deleted",true));
                if (count==0){
                    DeviceAttributeCategory deviceAttributeCategoryParent=new DeviceAttributeCategory();
                    deviceAttributeCategoryParent.setId(deviceAttributeCategoryVO.getParentId());
                    deviceAttributeCategoryParent.setHasEnableChild(false);
                    baseMapper.updateById(deviceAttributeCategoryParent);
                }
            }

            return updateCount;
        }

        return 0;
    }

    @Override
    @Transactional
    public int update(DeviceAttributeCategoryForm deviceAttributeCategoryForm) {
        DeviceAttributeCategoryVO deviceAttributeCategoryVO=baseMapper.get4appById(deviceAttributeCategoryForm.getId());
        if (deviceAttributeCategoryVO!=null){
            if (!deviceAttributeCategoryVO.getParentId().equals(deviceAttributeCategoryForm.getParentId())){
                boolean isUpdateEnable=deviceAttributeCategoryVO.getIsDeleted().equals(deviceAttributeCategoryForm.getIsDeleted());
                DeviceAttributeCategory deviceMaterialCategory=new DeviceAttributeCategory();
                BeanUtils.copyProperties(deviceAttributeCategoryForm,deviceMaterialCategory);
                baseMapper.updateById(deviceMaterialCategory);

                //update new parent category
                if (deviceAttributeCategoryForm.getParentId()!=ROOT_ID){
                    DeviceAttributeCategory parentDeviceAttributeCategory=new DeviceAttributeCategory();
                    parentDeviceAttributeCategory.setId(deviceAttributeCategoryForm.getParentId());
                    parentDeviceAttributeCategory.setHasChild(true);
                    if (deviceAttributeCategoryForm.getIsDeleted()){
                        parentDeviceAttributeCategory.setHasEnableChild(true);
                    }
                    baseMapper.updateById(parentDeviceAttributeCategory);
                }


                //update current db product category
                if (deviceAttributeCategoryVO.getParentId()!=ROOT_ID){
                    int count=baseMapper.selectCount(new QueryWrapper<DeviceAttributeCategory>().eq("parent_id",deviceAttributeCategoryVO.getParentId()));
                    if (count==0){
                        DeviceAttributeCategory deviceAttributeCategoryParent=new DeviceAttributeCategory();
                        deviceAttributeCategoryParent.setId(deviceAttributeCategoryVO.getParentId());
                        deviceAttributeCategoryParent.setHasChild(false);
                        baseMapper.updateById(deviceAttributeCategoryParent);
                    }
//                if (isUpdateEnable&&!deviceCategoryForm.getIsDeleted()){
                    count=baseMapper.selectCount(new QueryWrapper<DeviceAttributeCategory>().eq("parent_id",deviceAttributeCategoryVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        DeviceAttributeCategory deviceAttributeCategoryParent=new DeviceAttributeCategory();
                        deviceAttributeCategoryParent.setId(deviceAttributeCategoryVO.getParentId());
                        deviceAttributeCategoryParent.setHasEnableChild(false);
                        baseMapper.updateById(deviceAttributeCategoryParent);
                    }
                    //                }
                }


            }else{
                boolean isUpdateEnable=deviceAttributeCategoryVO.getIsDeleted().equals(deviceAttributeCategoryForm.getIsDeleted());
                DeviceAttributeCategory deviceAttributeCategory=new DeviceAttributeCategory();
                BeanUtils.copyProperties(deviceAttributeCategoryForm,deviceAttributeCategory);
                baseMapper.updateById(deviceAttributeCategory);
                if (isUpdateEnable&&!deviceAttributeCategoryForm.getIsDeleted()&&deviceAttributeCategoryForm.getParentId()!=ROOT_ID){
                    int count=baseMapper.selectCount(new QueryWrapper<DeviceAttributeCategory>().eq("parent_id",deviceAttributeCategoryVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        DeviceAttributeCategory deviceAttributeCategoryParent=new DeviceAttributeCategory();
                        deviceAttributeCategoryParent.setId(deviceAttributeCategoryVO.getParentId());
                        deviceAttributeCategoryParent.setHasEnableChild(false);
                        baseMapper.updateById(deviceAttributeCategoryParent);
                    }
                }

            }
        }
        return 0;
    }

    @Override
    public JsonResult getTreeData(Integer type){
        Map<String ,Object> mapQuery = new HashMap<>();
        mapQuery.put("type",type);
        List<DeviceAttributeCategoryVO> list=baseMapper.list4app(mapQuery);
        Map<Long,List<NodeDataVO>> map=new HashMap<>();
        for (DeviceAttributeCategoryVO category:list) {
            if (map.containsKey(category.getParentId())){
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(category.getId().toString());
                nodeDataVO.setName(category.getName());
                map.get(category.getParentId()).add(nodeDataVO);
            }else{
                List<NodeDataVO> tmpList=new ArrayList<>();
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(category.getId().toString());
                nodeDataVO.setName(category.getName());
                tmpList.add(nodeDataVO);
                map.put(category.getParentId(),tmpList);
            }
        }
        List<NodeDataVO> rootList=map.get(-1L);
        if (rootList==null){
            return JsonResult.success();
        }
        constructTree(rootList,map);
        return JsonResult.success(rootList);
    }

    private void  constructTree(List<NodeDataVO> parentList,Map<Long,List<NodeDataVO>> dataMap){
        for (NodeDataVO node:parentList) {
            Long nodeId=Long.valueOf(node.getValue());
            List<NodeDataVO> childList=dataMap.get(nodeId);
            if (childList!=null){
                node.setChildren(childList);
                constructTree(childList,dataMap);
            }
        }
    }
}
